package org.dfl.plugin.dialogs;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.dfl.messages.Messages;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;

/**
 * dialogs manager that shows error dialogs
 * @author Piotr Wlodarczyk
 *
 */
public class DialogsManager {
	private static Logger Log = Logger.getLogger(DialogsManager.class);
	
	public static void openErrorDialog(Throwable e){
		Log.error(e.getMessage(),e);
		openErrorDialog(Messages.PopupDialogManager_error,e.getMessage()==null?Messages.PopupDialogManager_errorUnknown+e.getClass():e.getMessage());
	}
	
	public static void openErrorDialog(final String text){
		openErrorDialog(Messages.PopupDialogManager_error,text==null?Messages.PopupDialogManager_errorUnknown2:text);
	}
	
	public static void openErrorDialog(final String title, final String text){
		openDialog(title, text, SWT.ICON_ERROR | SWT.OK);
	}
	
	public static boolean openOkCancelDialog(final String title, final String text){
		return openDialog(title,text,SWT.ICON_QUESTION | SWT.YES | SWT.NO) == SWT.YES;
	}
	
	public static int openDialog(final String title, final String text, final int prop){
		final int res[] = {0};
		Display.getDefault().syncExec(new Runnable() {
			public void run() {
				final Display display = Display.getCurrent() != null ? Display
						.getCurrent() : Display.getDefault();
				MessageBox box = new MessageBox(new Shell(display), prop);
				box.setMessage(text);
				box.setText(title);
				res[0] = box.open();
			}
		}); // notice SYNC exec
		return res[0];
	}
	
	@SuppressWarnings("unchecked")
	public static String openSelectDialog(final String title, final String text, Collection col, boolean readonly) {
		final Display display = Display.getCurrent()!=null?Display.getCurrent():Display.getDefault();
		InputDialog dialog=new InputDialog(display.getActiveShell(),title,text,col,readonly);
		dialog.setBlockOnOpen(true);
		if (dialog.open() == Window.OK) {
			return dialog.getValue();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static Object openSelectDialog(final String title, final String text, Collection col) {
		final Display display = Display.getCurrent()!=null?Display.getCurrent():Display.getDefault();
		ElementListSelectionDialog dialog=new ElementListSelectionDialog(display.getActiveShell(), new LabelProvider());
		dialog.setElements(col.toArray());
		dialog.setTitle(title);
		dialog.setMessage(text);
		dialog.setMultipleSelection(false);
		dialog.setBlockOnOpen(true);
		if (dialog.open() == Window.OK) {
			return dialog.getFirstResult();
		}
		return null;
	}
}
